package cn.edu.ctbu.scoremg.api;


import cn.edu.ctbu.scoremg.constant.REnum;
import cn.edu.ctbu.scoremg.entity.Student;
import cn.edu.ctbu.scoremg.exception.RException;
import cn.edu.ctbu.scoremg.service.StudentService;
import cn.edu.ctbu.scoremg.util.RUtil;
import cn.edu.ctbu.scoremg.vo.QueryObj;
import cn.edu.ctbu.scoremg.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@RestController
@RequestMapping("/api/student")
public class StudentApiController {
    @Autowired
    private StudentService studentService;
    @GetMapping("/list")
    public R<List<Student>> findAll(){
        List<Student> students = studentService.getAll();
        return RUtil.success(students);
    }
    @PostMapping("/add")
    public R<Student> add(Student student) {
        return RUtil.success(studentService.add(student));
    }


    @GetMapping("/{id}")
    public R<Student> findById(@PathVariable Integer id) {
        return RUtil.success(studentService.findById(id));
    }

    @PutMapping("/update")
    public R<Student> update(Student student) {
        return RUtil.success(studentService.update(student));
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id) {
        studentService.delete(id);
        return RUtil.success();
    }

    @DeleteMapping("/deleteId/{ids}")
    public R deleteByIds(@PathVariable String ids) {
        try {
            List<Integer> teachIds = Stream.of(ids.split(","))
                    .map(Integer::parseInt).collect(Collectors.toList());
            studentService.deleteByIds(teachIds);
        } catch (Exception e) {
            return RUtil.error(1, e.getMessage());
        }
        return RUtil.success();
    }
    @GetMapping("/validateUser")
    public R validateSnoAndPassword(String sno, String password, HttpServletRequest request) throws Exception{
        Student student =studentService.validateUsernameAndPassword(sno, password);
        request.getSession().setAttribute("userInfo", student);
        return RUtil.success();
    }


    public StudentService getStudentService() {
        return studentService;
    }

    @PostMapping("/getbypage")
    public R<Page<Student>> getByPage(@RequestBody QueryObj<Student> qObj) {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Integer pageIndex =0;
        Integer pageSize =10;
        if (qObj==null){
            Pageable pageable= PageRequest.of(pageIndex,pageSize,sort);
            Page<Student> students = studentService.getAll(pageable);
            return RUtil.success(students.getContent(),students.getTotalElements());
        }else {
            pageIndex=qObj.getPage()-1;
            pageSize=qObj.getLimit();
            if (qObj.getData() instanceof Student){
                Student student = (Student) qObj.getData();
                Pageable pageable= PageRequest.of(pageIndex,pageSize,sort);
                ExampleMatcher matcher=ExampleMatcher.matching()
                        .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains())
                        .withIgnoreNullValues();
                Example<Student> example=Example.of(student,matcher);
                Page<Student> studentPage = studentService.getAll(example,pageable);
                return RUtil.success(studentPage.getContent(),studentPage.getTotalElements());
            }else {
                throw new RException(REnum.QUERY_ERR);
            }
        }
    }
}
